import React, { useEffect } from 'react';
import { 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber, 
  Button, 
  Space, 
  Row, 
  Col,
  Typography,
  message
} from 'antd';
import { Course } from '../types/schedule';

const { Option } = Select;
const { Text } = Typography;

interface CourseEditModalProps {
  visible: boolean;
  course: Course | null;
  onCancel: () => void;
  onSave: (course: Course) => void;
}

const CourseEditModal: React.FC<CourseEditModalProps> = ({
  visible,
  course,
  onCancel,
  onSave
}) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible && course) {
      form.setFieldsValue({
        ...course,
        weeksText: course.weeks.join(', ')
      });
    } else if (visible) {
      form.resetFields();
    }
  }, [visible, course, form]);

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 解析周次文本
      const weeksText = values.weeksText || '';
      const weeks = weeksText
        .split(',')
        .map((week: string) => parseInt(week.trim()))
        .filter((week: number) => !isNaN(week) && week > 0);
      
      const updatedCourse: Course = {
        ...course!,
        ...values,
        weeks,
        id: course?.id || `course_${Date.now()}`
      };
      
      onSave(updatedCourse);
      message.success('课程信息更新成功');
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const weekDays = [
    { value: 1, label: '周一' },
    { value: 2, label: '周二' },
    { value: 3, label: '周三' },
    { value: 4, label: '周四' },
    { value: 5, label: '周五' },
    { value: 6, label: '周六' },
    { value: 7, label: '周日' }
  ];

  const timeSlots = [
    { value: 1, label: '第1节 (08:00-08:45)' },
    { value: 2, label: '第2节 (08:55-09:40)' },
    { value: 3, label: '第3节 (10:00-10:45)' },
    { value: 4, label: '第4节 (10:55-11:40)' },
    { value: 5, label: '第5节 (14:00-14:45)' },
    { value: 6, label: '第6节 (14:55-15:40)' },
    { value: 7, label: '第7节 (16:00-16:45)' },
    { value: 8, label: '第8节 (16:55-17:40)' },
    { value: 9, label: '第9节 (19:00-19:45)' },
    { value: 10, label: '第10节 (19:55-20:40)' },
    { value: 11, label: '第11节 (20:50-21:35)' },
    { value: 12, label: '第12节 (21:45-22:30)' }
  ];

  return (
    <Modal
      title={course ? '编辑课程' : '添加课程'}
      open={visible}
      onCancel={onCancel}
      width={800}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="save" type="primary" onClick={handleSave}>
          保存
        </Button>
      ]}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: 'required',
          duration: 2,
          credits: 3
        }}
      >
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="课程名称"
              name="name"
              rules={[{ required: true, message: '请输入课程名称' }]}
            >
              <Input placeholder="请输入课程名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="任课教师"
              name="teacher"
              rules={[{ required: true, message: '请输入任课教师' }]}
            >
              <Input placeholder="请输入任课教师" />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="教室"
              name="classroom"
              rules={[{ required: true, message: '请输入教室' }]}
            >
              <Input placeholder="请输入教室" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="学分"
              name="credits"
              rules={[{ required: true, message: '请输入学分' }]}
            >
              <InputNumber 
                min={0.5} 
                max={10} 
                step={0.5}
                placeholder="学分"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={8}>
            <Form.Item
              label="课程类型"
              name="type"
              rules={[{ required: true, message: '请选择课程类型' }]}
            >
              <Select placeholder="请选择课程类型">
                <Option value="required">必修</Option>
                <Option value="elective">选修</Option>
                <Option value="practice">实践</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="星期"
              name="dayOfWeek"
              rules={[{ required: true, message: '请选择星期' }]}
            >
              <Select placeholder="请选择星期">
                {weekDays.map(day => (
                  <Option key={day.value} value={day.value}>
                    {day.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              label="开始节次"
              name="timeSlot"
              rules={[{ required: true, message: '请选择开始节次' }]}
            >
              <Select placeholder="请选择开始节次">
                {timeSlots.map(slot => (
                  <Option key={slot.value} value={slot.value}>
                    {slot.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label="持续节数"
              name="duration"
              rules={[{ required: true, message: '请输入持续节数' }]}
            >
              <InputNumber 
                min={1} 
                max={4} 
                placeholder="持续节数"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="上课周次"
              name="weeksText"
              rules={[{ required: true, message: '请输入上课周次' }]}
              extra="用逗号分隔，例如: 1,2,3,4 或 1-8,10-16"
            >
              <Input placeholder="例如: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16" />
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          label="课程描述"
          name="description"
        >
          <Input.TextArea 
            rows={3} 
            placeholder="请输入课程描述（可选）"
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CourseEditModal;
